package mortal.common.preLoadPage
{
	import Framework.MQ.*;
	import Framework.Util.*;
	
	import Message.Command.*;
	import Message.Login.*;
	import Message.Public.*;
	
	import com.gengine.debug.*;
	
	import extend.php.*;
	
	import flash.display.*;
	import flash.events.*;
	import flash.net.*;
	import flash.text.*;
	import flash.utils.*;
	
	import mortal.common.error.*;
	import mortal.common.global.*;
	import mortal.game.net.rmi.login.*;
	import mortal.mvc.core.*;
	
	public class PreLoginProxy extends EventDispatcher
	{
		public var rootStage:Stage;
		private var _gameSession:GameSession;
		private var _slogin:SLogin;
		public var sloginReturn:SLoginReturn;
		private var _createRole:MovieClip;
		public var isLoginSuccess:Boolean = false;
		private var urlloader:URLLoader;
		private var _isLoadedApp:Boolean = false;
		private static var _instance:PreLoginProxy;
		public static const LOGIN_SUCCESS:String = "loginSuccess";
		
		public function PreLoginProxy()
		{
			this.urlloader = new URLLoader();
			if (_instance)
			{
				throw new Error("单例！");
			}
			
			ErrorCode.init();
		}
		
		public function login() : void
		{
			this._gameSession = new GameSession();
			this._gameSession.loginSession.url = ParamsConst.instance.loginIP;
			LoginRMI.instance.rmiSession = this._gameSession.loginSession;
			Log.debug("登陆服务器：" + this._gameSession.loginSession.url);
			this._slogin = new SLogin();
			if (ParamsConst.instance.guest == 1)
			{
				this._slogin.username = ParamsConst.instance.username;
				this._slogin.password = ParamsConst.DefaultPassWord;
				this._slogin.loginIp = ParamsConst.instance.loginIP;
				this._slogin.gateIp = ParamsConst.instance.gameIP;
				this._slogin.time = ParamsConst.instance.time as Date;
			}
			else
			{
				this._slogin.username = ParamsConst.instance.username;
				this._slogin.userId = ParamsConst.instance.userId;
				this._slogin.server = ParamsConst.instance.server;
				this._slogin.time = ParamsConst.instance.time as Date;
				this._slogin.flag = ParamsConst.instance.flag;
				this._slogin.country = ParamsConst.instance.defaultCamp;
				this._slogin.isAdult = ParamsConst.instance.isAdult;
				this._slogin.version = 0;
				this._slogin.platformCode = ParamsConst.instance.platformCode;
				this._slogin.password = ParamsConst.instance.password;
				this._slogin.loginIp = ParamsConst.instance.loginIP;
				this._slogin.totalOnlineTime = ParamsConst.instance.totalOnlineTime;
				this._slogin.platformUserName = ParamsConst.instance.platformUserName;
				this._slogin.issm = ParamsConst.instance.issm;
				this._slogin.playerId = ParamsConst.instance.player_id;
				this._slogin.gateIp = ParamsConst.instance.gameIP;
			}
			NetDispatcher.addCmdListener(EPublicCommand._ECmdPublicLoginInfoShow, this.onShowLoginInfo);
			if (PHPSender.isCreateRole)
			{
				PHPSender.sendToURLByPHP(SenderType.Login);
			}
			LoginRMI.instance.loginProxy.login_async(new AMI_ILogin_login(this.loginSuccess, this.loginException), this._slogin);
		
			// 跳过验证
			initApp();
		}
		
		public function loginSuccess(obj:Object, loginreturn:SLoginReturn) : void
		{
			if (this._gameSession.loginSession && this._gameSession.loginSession.session)
			{
				this._gameSession.loginSession.session.abandon();
			}
			this._gameSession.gmaeSession.url = SUrl(loginreturn.urls[0]).url;
			Log.debug("登陆游戏服务器：" + this._gameSession.gmaeSession.url);
			this.sloginReturn = loginreturn;
			this.removeCreateRole();
			if (GameLoadBar.instance && !GameLoadBar.instance.visible)
			{
				GameLoadBar.instance.visible = true;
			}
			this.isLoginSuccess = true;
			dispatchEvent(new Event(LOGIN_SUCCESS));
			if (PHPSender.isCreateRole)
			{
				PHPSender.sendToURLByPHP(SenderType.CreateRoleSuccess);
			}
			this.initApp();
		}
		
		public function createRoleException(except:Exception) : void
		{
			var textfile:TextField = null;
			var error:* = ErrorCode.getErrorByLogin(except.code);
			if (this._createRole && this._createRole.parent)
			{
				this._createRole.showException(error);
			}
			else if (!this.isLoginSuccess)
			{
				textfile = new TextField();
				textfile.autoSize = TextFieldAutoSize.LEFT;
				textfile.textColor = 16777215;
				textfile.background = true;
				textfile.backgroundColor = 0;
				textfile.x = this.rootStage.stageWidth / 2 - 100;
				textfile.y = this.rootStage.stageHeight / 2 - 40;
				textfile.text = "错误码：" + except.code + "\n错误信息：" + except.message;
				this.rootStage.addChild(textfile);
			}
			PHPSender.sendToURLByPHP(SenderType.CreateRoleFail, except.message);
		}
		
		public function loginException(except:Exception) : void
		{
			var data:Object = null;
			var textfile:TextField = null;
			if (except.code == ErrorCode.ErrorLogin_NoRole)
			{
				PHPSender.isCreateRole = true;
				if (ParamsConst.instance.guest == 1)
				{
					data = {};
					data.camp = ParamsConst.instance.defaultCamp;
					data.sex = ParamsConst.instance.defaultSex;
					data.name = ParamsConst.instance.roleName;
					this.sendCreateRole(data);
				}
				else
				{
					this.createRole();
				}
				PHPSender.sendToURLByPHP(SenderType.CreateRole);
			}
			else
			{
				if (!this.isLoginSuccess)
				{
					textfile = new TextField();
					textfile.autoSize = TextFieldAutoSize.LEFT;
					textfile.textColor = 16777215;
					textfile.background = true;
					textfile.backgroundColor = 0;
					textfile.x = this.rootStage.stageWidth / 2 - 100;
					textfile.y = this.rootStage.stageHeight / 2 - 40;
					textfile.text = "错误码：" + except.code + "\n错误信息：" + except.message;
					this.rootStage.addChild(textfile);
				}
				if (PHPSender.isCreateRole)
				{
					PHPSender.sendToURLByPHP(SenderType.LoginFail, textfile.text);
				}
			}
		}
		
		public function createRole() : void
		{
			var loader:* = new Loader();
			loader.contentLoaderInfo.addEventListener(Event.COMPLETE, this.onRoleCompleteHandler);
			loader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, this.onRoleProgressHandler);
			loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, this.onLoadRoleHandler);
			loader.load(new URLRequest(PathConst.createRoleUrl));
			trace(PathConst.createRoleUrl);
			PHPSender.sendToURLByPHP(SenderType.LoadCreateRole);
		}
		
		private function onRoleCompleteHandler(event:Event) : void
		{
			if (GameLoadBar.instance && GameLoadBar.instance.visible)
			{
				GameLoadBar.instance.visible = false;
			}
			var loaderinfo:* = event.target as LoaderInfo;
			loaderinfo.removeEventListener(Event.COMPLETE, this.onRoleCompleteHandler);
			loaderinfo.removeEventListener(ProgressEvent.PROGRESS, this.onRoleProgressHandler);
			loaderinfo.removeEventListener(IOErrorEvent.IO_ERROR, this.onLoadRoleHandler);
			this._createRole = loaderinfo.content as MovieClip;
			this._createRole.mainPath = ParamsConst.instance.mainPath;
			this._createRole.version = ParamsConst.instance.version;
			this._createRole.randomNameUrl = ParamsConst.instance.randomNameUrl;
			this.rootStage.addChild(this._createRole);
			this._createRole.setDefaultParams(ParamsConst.instance.roleName, ParamsConst.instance.defaultSex, ParamsConst.instance.defaultCamp);
			this._createRole.submitFun = this.submitFun;
			this._createRole.addEventListener(MouseEvent.CLICK, this.onCreateRoleClickHandler);
			PHPSender.sendToURLByPHP(SenderType.LoadCreateRoleSuccess);
			this.initApp();
		}
		
		private function onLoadRoleHandler(event:ErrorEvent) : void
		{
			PHPSender.sendToURLByPHP(SenderType.LoadCreateRoleFail, event.text);
		}
		
		private function onCreateRoleClickHandler(event:MouseEvent) : void
		{
			PHPSender.sendToURLByPHP(SenderType.ClickCreateRole);
			this._createRole.removeEventListener(MouseEvent.CLICK, this.onCreateRoleClickHandler);
		}
		
		public function onShowLoginInfo(message:MessageBlock) : void
		{
			var infoshow:* = message.messageBase as SLoginInfoShow;
			if (this._createRole && this._createRole.parent)
			{
				Object(this._createRole).addShowInfo(infoshow.camp, infoshow.sex, infoshow.name);
			}
		}
		
		private function removeCreateRole() : void
		{
			if (this._createRole && this._createRole.parent)
			{
				this._createRole.parent.removeChild(this._createRole);
				this._createRole = null;
			}
		}
		
		private function onRoleProgressHandler(event:ProgressEvent) : void
		{
			GameLoadBar.instance.setProgress(PreloaderConfig.LOAD_CREATE_ROLE, event.bytesLoaded, event.bytesTotal);
		}
		
		private function submitFun(data:Object) : void
		{
			this.sendCreateRole(data);
		}
		
		private function sendCreateRole(data:Object) : void
		{
			var role:SFirstRole = new SFirstRole();
			role.camp = data.camp;
			role.sex = data.sex;
			role.name = data.name;
			role.career = ECareer._ECareerNewPlayer;
			LoginRMI.instance.loginProxy.createFirstRole_async(new AMI_ILogin_createFirstRole(this.loginSuccess, this.createRoleException), role);
		}
		
		public function get gameSession() : GameSession
		{
			return this._gameSession;
		}
		
		public function set gameSession(session:GameSession) : void
		{
			this._gameSession = session;
		}
		
		public function get slogin() : SLogin
		{
			return this._slogin;
		}
		
		public function set slogin(slogin:SLogin) : void
		{
			this._slogin = slogin;
		}
		
		private function initApp() : void
		{
			// 跳过加载MainGame.swf
			var mainGame:MainGame = new MainGame();
			this.rootStage.addChild(mainGame);
			
			// -------------------------------
			
			
			var request:URLRequest = null;
			if (this._isLoadedApp == false)
			{
				this._isLoadedApp = true;
				this.urlloader.dataFormat = URLLoaderDataFormat.BINARY;
				request = new URLRequest(PathConst.gameUrl + "?v=" + ParamsConst.instance.flashVersion);
				this.urlloader.addEventListener(Event.COMPLETE, this.onCompleteHandler);
				this.urlloader.addEventListener(ProgressEvent.PROGRESS, this.onProgressHandler);
				this.urlloader.addEventListener(IOErrorEvent.IO_ERROR, this.onIOErrorHandler);
				this.urlloader.load(request);
			}
		}
		
		private function onCompleteHandler(event:Event) : void
		{
			if (PHPSender.isCreateRole)
			{
				PHPSender.sendToURLByPHP(SenderType.LoadMaigGameSwfSuccess);
			}
			var loader:* = new Loader();
			loader.loadBytes(event.target.data as ByteArray);
			this.rootStage.addChild(loader);
		}
		
		private function onProgressHandler(event:ProgressEvent) : void
		{
			GameLoadBar.instance.setProgress(PreloaderConfig.LOAD_MAIN_GAME, event.bytesLoaded, event.bytesTotal);
		}
		
		private function onIOErrorHandler(event:IOErrorEvent) : void
		{
			if (PHPSender.isCreateRole)
			{
				PHPSender.sendToURLByPHP(SenderType.LoadMaigGameSwfFail, event.text);
			}
			trace("preloader:" + event.text);
		}
		
		public static function get instance() : PreLoginProxy
		{
			if (!_instance)
			{
				_instance = new PreLoginProxy;
			}
			return _instance;
		}
		
	}
}
